<template>
  <PageTable
    :columns="columns.filter((item) => item.checked)"
    :data-source="sourceData"
    :loading="loading"
    :row-selection="{
      selectedRowKeys,
      getCheckboxProps: ({ admin }) => ({ disabled: admin }),
      onChange: setSelectedRowKeys
    }"
    :pagination="{
      size: 'middle',
      current: pagination.pageNum,
      pageSize: pagination.pageSize,
      total: pagination.total,
      showSizeChanger: true,
      onChange: onPageChange
    }"
  >
    <template #search>
      <div class="search-container">
        <AForm layout="inline" :model="searchState" @finish="onSearchData">
          <ASpaceCompact>
            <ASelect style="width: 120px" :value="searchType" :options="options" @change="setSearchType"></ASelect>
            <AFormItem :name="searchType" style="margin-right: 0">
              <AInput v-model:value="searchState[searchType]" />
            </AFormItem>
            <AButton :icon="createVNode(SearchOutlined)" html-type="submit"></AButton>
          </ASpaceCompact>
        </AForm>
        <AButton type="link" @click="() => setCollapse(!collapse)">
          <span>高级搜索</span>
          <DownOutlined class="collapse-target-icon" :collapse="collapse" />
        </AButton>
      </div>
      <RCollapse :collapse="collapse">
        <AForm layout="inline" ref="formRef" :model="formState" @finish="onSearchData" @reset="onReset">
          <AFormItem label="文件名称" name="fileName">
            <AInput v-model:value="formState.userName" placeholder="请输入文件名称"></AInput>
          </AFormItem>
          <AFormItem label="文件哈希" name="fileHash">
            <AInput v-model:value="formState.phoneNumber" placeholder="请输入文件哈希"></AInput>
          </AFormItem>
          <AFormItem>
            <ASpace>
              <AButton html-type="reset">重置</AButton>
              <AButton type="primary" html-type="submit">搜索</AButton>
            </ASpace>
          </AFormItem>
        </AForm>
      </RCollapse>
    </template>
    <template #operate>
      <ASpace>
        <AButton type="primary" ghost :icon="createVNode(UploadOutlined)" @click="() => setOpenUploadModal(true)">
          文件上传
        </AButton>
        <APopconfirm title="您确定批量删除数据吗?" ok-text="是" cancel-text="否" @confirm="onBatchDelete">
          <AButton danger ghost :icon="createVNode(DeleteOutlined)" :disabled="!selectedRowKeys.length">删除</AButton>
        </APopconfirm>
      </ASpace>
      <ASpace>
        <ATooltip title="刷新列表">
          <AButton :icon="createVNode(ReloadOutlined)" :disabled="!!timer" @click="onRefreshData">
            {{ timer || '' }}
          </AButton>
        </ATooltip>
        <RDropdownCheckbox
          placement="bottomRight"
          v-model:value="columns"
          :fieldNames="{ label: 'title', value: 'key', checked: 'checked' }"
        >
          <AButton :icon="createVNode(AppstoreOutlined)"></AButton>
        </RDropdownCheckbox>
      </ASpace>
    </template>
    <template #bodyActionCell="{ record }">
      <AButton type="link" size="small" :icon="createVNode(DownloadOutlined)" @click="() => onDownload(record)">
        下载
      </AButton>
      <APopconfirm title="您确定删除该数据吗?" ok-text="是" cancel-text="否" @confirm="() => onDelete(record)">
        <AButton type="link" danger size="small" :icon="createVNode(DeleteOutlined)">删除</AButton>
      </APopconfirm>
    </template>
  </PageTable>

  <FileUpload
    :open="openUploadModal"
    @finish="() => onRefreshData(true)"
    @cancel="() => setOpenUploadModal(false)"
  ></FileUpload>
</template>

<script setup>
import { createVNode, ref, reactive, toValue, onBeforeMount } from 'vue';
import { FileUpload } from './modules';
import { PageTable } from '@/components/templates';
import { RCollapse } from '@/components/common';
import { RDropdownCheckbox } from '@/components/custom';

import {
  SearchOutlined,
  DownOutlined,
  UploadOutlined,
  DownloadOutlined,
  DeleteOutlined,
  AppstoreOutlined,
  ReloadOutlined
} from '@ant-design/icons-vue';
import { useState, useFetchPageData, useFetch } from '@/hooks';

import {
  FILE_DOWNLOAD_URL,
  fetchGetFileList,
  fetchDownloadCreate,
  fetchDeleteFile,
  fetchDeleteBatchFile
} from '@/api/file';

const options = [
  { label: '综合搜索', value: 'keyword', placeholder: '综合搜索' },
  { label: '文件名称', value: 'fileName', placeholder: '请输入文件名称' },
  { label: '文件哈希', value: 'fileHash', placeholder: '请输入文件哈希' }
];

const defaultColumns = [
  { key: 'index', title: '序号', dataIndex: 'index', checked: true },
  { key: 'fileId', title: 'ID', dataIndex: 'fileId', checked: false },
  { key: 'fileTypeLabel', title: '文件类型', dataIndex: 'fileTypeLabel', checked: true },
  { key: 'fileName', title: '文件名称', dataIndex: 'fileName', checked: true },
  { key: 'fileHash', title: '文件哈希', dataIndex: 'fileHash', checked: true },
  { key: 'fileSize', title: '文件大小', dataIndex: 'fileSize', checked: true },
  { key: 'createTime', title: '创建时间', dataIndex: 'createTime', checked: true },
  { key: 'action', title: '操作', dataIndex: 'action', checked: true }
];

const columns = ref(defaultColumns);
const [collapse, setCollapse] = useState(false);
const [searchType, setSearchType] = useState('keyword');
const searchState = reactive({});
const formRef = ref();
const formState = reactive({});
const [openUploadModal, setOpenUploadModal] = useState(false);

const [selectedRowKeys, setSelectedRowKeys] = useState([]);
const {
  sourceData,
  loading: loading,
  pagination,
  timer,
  onFetchData,
  onSearchData,
  onPageChange,
  onResetData,
  onRefreshData
} = useFetchPageData(fetchGetFileList);

onBeforeMount(() => {
  onFetchData();
});

const onReset = () => {
  onResetData();
  toValue(formRef).resetFields();
};

const { onFetch: onFetchDownload } = useFetch(fetchDownloadCreate);
const onDownload = async (values) => {
  const taskId = await onFetchDownload(values.fileId);

  const root = document.body;
  const link = document.createElement('a');
  link.href = FILE_DOWNLOAD_URL + taskId;
  root.appendChild(link);
  link.click();
  root.removeChild(link);
};

const onDelete = async (values) => {
  await fetchDeleteFile(values.fileId);
  onRefreshData(true);
};

const onBatchDelete = async () => {
  if (toValue(selectedRowKeys).length) {
    await fetchDeleteBatchFile(toValue(selectedRowKeys));
    onRefreshData(true);
  }
};
</script>

<style lang="scss" scoped>
.search-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.ant-form .ant-space-compact .ant-form-item {
  margin-inline-end: -1px;
}

.collapse-target-icon {
  transform: rotate(0deg);
  transform-origin: center center;
  transition: transform 0.3s;

  &[collapse='true'] {
    transform: rotate(180deg);
  }
}
</style>
